package json;

import com.google.common.collect.Lists;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * @Author: ycy
 * @CreateDate: 2019/5/30 18:20
 */
public class ExclusionStrategyDemo {

  public static void main(String[] args) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setExclusionStrategies(new CustomExclusionStrategy()).create();
    EntityDemo entityDemo = new EntityDemo();
    entityDemo.name = "thinking in java";
    entityDemo.title = "java入门精选";
    entityDemo.tag = "it";
    entityDemo.content = "ctrip://wireless/h5?path=inn&page=index.html#inn/list/6&cityname=大连&channelid=60&fromNative=true&isHideNavBar=YES&from_native_page=1&type=8&value=12304|||星海广场、圣亚海洋世界、星海公园";
    System.out.println(gson.toJson(entityDemo));

    String jsonStr = "{\"name\":\"thinking in java\",\"districtName\":\"it\",\"content\":\"文章内容......\",\"title\":\"java入门精选\"}";
    EntityDemo jsonStrTOentity = gson.fromJson(jsonStr, EntityDemo.class);
    System.out.println(jsonStrTOentity);

  }

  private static class CustomExclusionStrategy implements ExclusionStrategy {

    //json字符串转对象时 和转化成json字符串时,定义那些字段输出
    List<String> containField = Lists.newArrayList("name", "title", "tag", "content");

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
      if (containField.contains(f.getName())) {
        return false;
      }
      return true;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
      return false;
    }
  }

  private static class EntityDemo {

    @Expose(serialize = true)
//    @Expose(serialize = false) //json字符串转对象时 和转化成json字符串时,定义是否输出
    private String name;

    @Expose(deserialize = false)
    public String title;

    @Expose
    @SerializedName(value = "districtName", alternate = {"districtname"})
    //转化成json字符串,tag 变为 districtName,和json字符串转对象时,dostrictName变为tag
    private String tag;

    @Expose
    private String content;

    @Override
    public String toString() {
      return "EntityDemo{" +
              "name='" + name + '\'' +
              ", tag='" + tag + '\'' +
              ", content='" + content + '\'' +
              ", title='" + title + '\'' +
              '}';
    }
  }

}
